//
//  GiveOrTakeCarInfoVC.m
//  动态布局
//
//  Created by LeeBruce on 16/9/1.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "GiveOrTakeCarInfoVC.h"
#import "CarInfoCell.h"
#import "DetailVC.h"
#import "TrackViewController.h"
#import "TopBackView.h"
#import "RootViewController.h"
#import "Common.h"
#import "CollectionReusableView.h"
#import "CollectionViewCell.h"
#import "ScrollImageViewController.h"
#import "WKProgressHUD.h"
#import "NullView.h"



@interface GiveOrTakeCarInfoVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) UIScrollView *scrollView;

@property (nonatomic,strong) NullView *nullView;


@end

@implementation GiveOrTakeCarInfoVC

- (void)viewDidLoad {
    [super viewDidLoad];

    self.nullView = [[NullView  alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight  - 45 * kHeight) andTitle:@""];
    self.nullView.backgroundColor = GrayColor;
    
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;

    
    TopBackView *topBackView= [[TopBackView alloc]initViewWithFrame:CGRectMake(0, 0, screenWidth, 64) andTitle:self.titleString];
    
    topBackView.rightButton.hidden = YES;
    [topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:topBackView];
    
    self.dataArray = [NSMutableArray array];
    
    [self initDataSources];
    
    [self initTableView];

}

-(void)initDataSources
{

//    //假数据
//    NSDictionary *dic = [NSDictionary dictionary];
//    dic =  [Common txtChangToJsonWithString:@"jiao_liebiao"];
//    
//    if ([dic[@"data"] count] > 0) {
//        
//        for (int i = 0; i < [dic[@"data"] count]; i ++) {
//            
//
//        }
//        
//        self.dataArray = [NSMutableArray arrayWithArray:dic[@"data"]];
//        
//        
////        [self getValueString];
//    }

    
    //网络数据
    
    
    self.nullView.label.text = @"暂无信息";

    NSString *urlString ;
    if ([self.titleString isEqualToString:@"交车信息"]) {
        
        urlString = [NSString stringWithFormat:@"%@?id=%@",order_delist,self.orderId];

    } else {
        urlString = [NSString stringWithFormat:@"%@?id=%@",order_exlist,self.orderId];

    }
    

    [Common requestWithUrlString:urlString contentType:application_json finished:^(id responseObj) {
        
        if ([responseObj[@"data"] isEqual:[NSNull null]] || [responseObj[@"data"] count] == 0) {
            
            [self.tableView addSubview:self.nullView];

        } else {
        
        
        if ([responseObj[@"data"] count] > 0) {
            
        self.dataArray = [NSMutableArray arrayWithArray:responseObj[@"data"]];
            
            
//            self.tableView.frame = CGRectMake(0, 0, screenWidth, (57 * kHeight  + cellHeight * 2 + 20)* self.dataArray.count);
//            self.tableView.frame = CGRectMake(0, 0, screenWidth, screenHeight);
            
//            UIButton *button = [self.view viewWithTag:300];
//            button.frame = CGRectMake(18, CGRectGetMaxY(self.tableView.frame) - 60, screenWidth - 36, Button_Height);
//            
//            CGFloat height = CGRectGetMaxY(button.frame) + 20;
//            if (height < screenHeight) {
//                height = screenHeight + 1;
//            }
//            self.scrollView.contentSize = CGSizeMake(screenWidth, height);
            
            [self.nullView removeFromSuperview];

        } else {
            
            [self.tableView addSubview:self.nullView];

        }

        [self.tableView reloadData];

        }
            
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
    
    
}

-(void)initTableView
{
    
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, screenHeight)];
    [self.view addSubview:self.scrollView];
    self.scrollView.backgroundColor = GrayColor;

    if (self.number == 2) {
        
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, screenHeight - 80, screenWidth, 80)];
        view.backgroundColor = GrayColor;
        view.tag = 300;
        [self.view addSubview:view];
        
        
        UIButton *jiaocheButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [jiaocheButton setTitle:@"确认交车" forState:UIControlStateNormal];
        jiaocheButton.titleLabel.font = Font(14);
//        jiaocheButton.tag = 300;
        jiaocheButton.backgroundColor = YellowColor;
        [jiaocheButton setTitleColor:WhiteColor forState:UIControlStateNormal];
        [jiaocheButton addTarget:self action:@selector(jiaocheButton) forControlEvents:UIControlEventTouchUpInside];
        jiaocheButton.frame = CGRectMake(18, (80 - Button_Height)/2.0, screenWidth - 36, Button_Height);
        [view addSubview:jiaocheButton];
        jiaocheButton.layer.cornerRadius = 5;
        
        
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight - 64 - 80) style:UITableViewStyleGrouped];

        
    } else {
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight - 64 ) style:UITableViewStyleGrouped];

    }
    
    
    
    self.tableView.delegate = self;
    
    self.tableView.dataSource = self;
    //    self.tableView.scrollEnabled = NO;
    self.tableView.backgroundColor = GrayColor;
    
    [self.scrollView addSubview:self.tableView];

    
}

//确认交车
-(void)jiaocheButton
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确认交车" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
//        [WKProgressHUD showInView:self.view withText:@"" animated:YES];
        
        Common *c = [[Common alloc]init];
        [c afPostRequestWithUrlString:receive_receipt parms:@{@"id":self.orderId} finishedBlock:^(id responseObj) {
            
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
            
            [WKProgressHUD popMessage:dic[@"message"] inView:self.view duration:1.5 animated:YES];

            
//            [WKProgressHUD dismissInView:self.view animated:YES];
            
            
            //延迟执行
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                if ([dic[@"success"] boolValue]) {
                    
                    
                    [self.navigationController popViewControllerAnimated:YES];
                    
                }
                
            });
    
            
        } failedBlock:^(NSString *errorMsg) {
            [WKProgressHUD dismissInView:self.view animated:YES];
            
            NSLog(@"%@",errorMsg);
        }];
        
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    
    [self presentViewController:alert animated:YES completion:nil];
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return  (self.dataArray.count > 0)? self.dataArray.count : 0;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    NSArray *arr = self.dataArray[section][@"sorders"];
    return arr.count;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *str = @"giveOrTakeCell";
    CarInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (!cell) {
        cell = [[CarInfoCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:str];
    }
    
    NSDictionary *dic = self.dataArray[indexPath.section];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.carStyleLabel.text = dic[@"sorders"][indexPath.row][@"name"];
    cell.vinLabel.text = dic[@"sorders"][indexPath.row][@"vin"];
    
    return cell;
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = [UIColor whiteColor];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(18, 0, 100, cellHeight)];
    label.text = self.titleString;
    label.textColor = littleBlackColor;
    label.font = Font(14);
    [view addSubview:label];
    
    UILabel *lineL = [[UILabel alloc]initWithFrame:CGRectMake(0, cellHeight - 0.5, screenWidth, 0.5)];
    lineL.backgroundColor = LineGrayColor;
    [view addSubview:lineL];
    
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(screenWidth - 100 - 18, 0, 100, cellHeight)];
    
    
    label1.text = [NSString stringWithFormat:@"%@",self.dataArray[section][@"statusText"]];
    label1.textColor = RedColor;
    label1.textAlignment = NSTextAlignmentRight;
    label1.font = Font(14);
    [view addSubview:label1];

    
    return view;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    
    UIView *view1 = [[UIView alloc]init];
    view1.backgroundColor = GrayColor;
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, cellHeight)];
    view.backgroundColor = [UIColor whiteColor];
    [view1 addSubview:view];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(18, 0, 100, cellHeight )];
    label.text = @"车辆总数:";
    label.textColor = littleBlackColor;
    label.font = Font(14);
    [view addSubview:label];
    
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(label.frame), 0, 80, cellHeight)];
    
    label1.text = [NSString stringWithFormat:@"%@辆",[self.dataArray[section]  objectForKey:@"amount"] ];
    label1.textColor = littleBlackColor;
    label1.font = Font(14);
    [view addSubview:label1];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"查看详情" forState:UIControlStateNormal];
    [button setBackgroundColor:YellowColor];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.titleLabel.font = Font(14);
    button.frame = CGRectMake(screenWidth - 70 * kWidth - 18, 6.5 * kHeight, 70 * kWidth, cellHeight - 13 * kHeight);
    [button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
    button.layer.cornerRadius = 5;
    button.tag = section + 400;
    
    return view1;
}

-(void)button:(UIButton *)sender{
    
    DetailVC *vc = [[DetailVC alloc]init];
    if ([self.titleString isEqualToString:@"交车信息"]) {
        vc.titleString = @"交车照片";
    } else {
        vc.titleString = @"提车照片";

    }
    
    vc.orderId = self.dataArray[sender.tag - 400][@"waybillId"];
        
    [self.navigationController pushViewController:vc animated:YES];
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 57 * kHeight;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return  cellHeight;
}


-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return cellHeight + 10;
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:YES];
    
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    [rootVC setTabBarHidden:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
